package com.bridgeintelligent.tag.customer.controller;

import cn.hutool.core.util.RandomUtil;
import com.bridgeintelligent.tag.constants.bulkload.MQConfig;
import com.bridgeintelligent.tag.constants.bulkload.StaticMqMsg;
import com.bridgeintelligent.tag.customer.constant.PublicConstant;
import com.bridgeintelligent.tag.customer.entity.CustomersCodes;
import com.bridgeintelligent.tag.customer.entity.Result;
import com.bridgeintelligent.tag.customer.exception.CustomersException;
import com.bridgeintelligent.tag.customer.mapper.CustomersMapper;
import com.bridgeintelligent.tag.customer.pojo.Customers;
import com.bridgeintelligent.tag.customer.scheduled.StaticCustomersScheduled;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wayneleo.quickstart.QuickException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.bridgeintelligent.tag.constants.PublicConstant.*;
import static com.bridgeintelligent.tag.customer.exception.CustomerErrors.ERROR_401006;
import static com.bridgeintelligent.tag.customer.exception.CustomerErrors.ERROR_401007;

@Api(tags = "静态客群定时任务手动执行")
@AllArgsConstructor
@RestController
@RequestMapping("/api/static")
@Slf4j
public class StaticCustomerScheduleController {

    private CustomersMapper mapper;
    private StaticCustomersScheduled scheduled;
    private ObjectMapper objectMapper;
    private RocketMQTemplate rocketMQTemplate;

    @ApiOperation("修改静态任务标记表的状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "flag", value = "类型 1：ES打标记 2：hdfs写文件")
    })
    @GetMapping("/updFlag")
    public Result updFlag(String flag) {
        return new Result(CustomersCodes.SUCCESS,mapper.updFlag(flag));
    }


    @ApiOperation("手动触发静态客群写文件入HDFS")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "cid", value = "客群ID")
    })
    @GetMapping("/triggerStaticHdfs")
    public Result triggerStaticHdfsScheduled(String cid) {
        try {
           if(StringUtils.isNotEmpty(cid)){
               StaticMqMsg dynamicStaticMqMsg = new StaticMqMsg(cid,mapper.findFlag(),cid+"_"+ RandomUtil.randomString(6));
               List<String> customerIds = mapper.findFailTask(Arrays.asList(PublicConstant.ZERO,THREE));
               if(!customerIds.contains(cid))return new Result(CustomersCodes.SUCCESS, "当前客群不符合重写HDFS文件操作条件");
               try {
                   String msg = objectMapper.writeValueAsString(dynamicStaticMqMsg);
                   rocketMQTemplate.convertAndSend(MQConfig.STATIC_CUSTOMERS_HDFS_TOPIC, msg);

               } catch (JsonProcessingException e) {
                   throw new RuntimeException(e);
               }catch(Exception e1){
                   throw QuickException.normal(ERROR_401007.args(cid));
               }
           }else{
               scheduled.doStaticHdfsWork();
           }

        } catch (CustomersException e) {
            return new Result(e.getCode(), "操作失败");
        }
        return new Result(CustomersCodes.SUCCESS);
    }

    @ApiOperation("手动触发静态客群打标记")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "cid", value = "客群ID"),
            @ApiImplicitParam(paramType = "query", name = "type", value = "类型 1：ES打标记 2：hdfs写文件")
    })
    @GetMapping("/triggerStaticMark")
    public Result triggerStaticMarkScheduled(String cid,String type) {
        return ONE.equals(type)?doEsMark(cid):doHdfsWork(cid);
    }

    private Result doEsMark(String cid){
        try {
            if(StringUtils.isEmpty(cid)) {
                return new Result(CustomersCodes.FAIL, "cid不能为空！！！");
            }
            Customers customers = mapper.findOneById(cid);
            if(Objects.isNull(customers)) {
                return new Result(CustomersCodes.FAIL, "客群不存在！！！");
            }
            if (PublicConstant.TRUE.equals(customers.getDateType())&&(!TWO.equals(customers.getIsMark()))) {
                //向MQ发送打标记的消息
                StaticMqMsg dynamicStaticMqMsg = new StaticMqMsg(cid,mapper.findFlag(),cid+"_"+ RandomUtil.randomString(6));
                try {
                    String msg = objectMapper.writeValueAsString(dynamicStaticMqMsg);
                    rocketMQTemplate.convertAndSend(MQConfig.STATIC_CUSTOMERS_TOPIC, msg);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        } catch (CustomersException e) {
            return new Result(e.getCode(), ERROR_401006.args(cid));
        }
        return new Result(CustomersCodes.SUCCESS);
    }

    private Result doHdfsWork(String cid){
        try {
            if(StringUtils.isNotEmpty(cid)){
                StaticMqMsg dynamicStaticMqMsg = new StaticMqMsg(cid,mapper.findFlag(),cid+"_"+ RandomUtil.randomString(6));
                List<String> customerIds = mapper.findFailTask(Arrays.asList(PublicConstant.ZERO,THREE));
                if(!customerIds.contains(cid))return new Result(CustomersCodes.SUCCESS, "当前客群不符合重写HDFS文件操作条件");
                try {
                    String msg = objectMapper.writeValueAsString(dynamicStaticMqMsg);
                    rocketMQTemplate.convertAndSend(MQConfig.STATIC_CUSTOMERS_TOPIC, msg);

                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }catch(Exception e1){
                    throw QuickException.normal(ERROR_401007.args(cid));
                }
            }else{
                scheduled.doStaticHdfsWork();
            }

        } catch (CustomersException e) {
            return new Result(e.getCode(), "操作失败");
        }
        return new Result(CustomersCodes.SUCCESS);
    }
}